package com.bblocks.util;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;

/**
 * 序号工具
 */
@Component
public class RedisSequenceUtil {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	public final String SEQ_MODEL = "BBLOCKS_SEQ_MODEL";
	public final long delta = 1; // 默认步长



	/***
	 * 获取当前序列号
	 * @param key Redis Key值
	 * @return
	 */
	public String getCurrentSequence(String key) {
		return this.getNextSequence(null,key, this.delta,-1,false);
	}

	/**
	 * 获取下一个序列号(如果格式化将为循环值)
	 * @param key Redis Key值
	 * @param length  <=0 不格式化
	 * @return
	 */
	public String getCurrentSequence(String key,int length) {
		return this.getNextSequence(key, length,true);
	}

	/**
	 * 获取下一个序列号
	 * @param key Redis Key值
	 * @param length <=0 不格式化
	 * @param canLoop true=数据将取余，否则不操作 （length>0生效）
	 * @return
	 */
	public String getNextSequence(String key,int length,boolean canLoop) {
		return this.getNextSequence(null,key, this.delta,length,canLoop);
	}



	/**
	 * 获取下一个序列号
	 * @param model
	 * @param key Redis Key值
	 * @param delta 增长步长
	 * @param length <=0 不格式化
	 * @param canLoop true=数据将取余，否则不操作 （length>0生效）
	 * @return
	 */
	public String getNextSequence(String model,String key, long delta,int length,boolean canLoop) {
		if(StrUtil.isEmpty(model))
			model = SEQ_MODEL;

		final String finalKey = model+":"+key;

		Long increNum = redisTemplate.opsForValue().increment(finalKey, delta);

		//不足补位
		//String increResult =  String.format("%1$06d", increNum);
		if(length > 0) {
			int max = Integer.parseInt(StrUtil.repeatByLength("9",length));
			int increInt = increNum.intValue();
			if(canLoop) {
				if(increInt>max)
					increInt = (increInt % max)+1;
			}

			String increResult = String.format("%0" + length + "d", increInt);
			return increResult;
		}else
			return String.valueOf(increNum) ;
	}


	public static void main(String[] args){
		int a = 1024;
		int max = 999;

		System.out.println(a%max);
		a = 4048;
		System.out.println(a%max);
	}


}